package com.cloudpivot.receivales.contract.service.http;

import com.cloudpivot.receivales.contract.configuration.CrmConfig;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.NTCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * crm 请求api服务
 */

@Component
@Slf4j
public class HttpAPIServiceForCrm {

    @Autowired
    private CrmConfig crmConfig;

    @Autowired
    private CloseableHttpClient httpClient;

    @Autowired
    private RequestConfig config;

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * crm专用 需求:需要增加请求头的get请求,同时增加crm获取分页
     * 不带参数的get请求，如果状态码为200，则返回body，如果不为200，则返回null
     *
     * @param url
     * @return
     * @throws Exception
     */
    public String doGetCrm(String url, String header, int pageSize) throws Exception {
        // 声明 http get 请求
        HttpGet httpGet = new HttpGet(url);

        // 装载配置信息
        httpGet.setConfig(config);
        httpGet.setHeader("MSCRMCallerID", header);
        httpGet.setHeader("Prefer", "odata.maxpagesize=" + pageSize);

        this.httpClient = this.crmConfig.getAuthHttp();

        // 发起请求
        CloseableHttpResponse response = this.httpClient.execute(httpGet);

        // 判断状态码是否为200
        if (response.getStatusLine().getStatusCode() >= 200 && response.getStatusLine().getStatusCode() <= 210) {
            // 返回响应体的内容
            return EntityUtils.toString(response.getEntity(), "UTF-8");
        }
        return null;
    }

    /**
     * crm专用 需求:需要增加请求头的get请求
     * 不带参数的get请求，如果状态码为200，则返回body，如果不为200，则返回null
     *
     * @param url
     * @return
     * @throws Exception
     */
    public String doGetCrm(String url, String header) throws Exception {
        // 声明 http get 请求
        HttpGet httpGet = new HttpGet(url);

        // 装载配置信息
        httpGet.setConfig(config);
        httpGet.setHeader("MSCRMCallerID", header);

        this.httpClient = this.crmConfig.getAuthHttp();

        // 发起请求
        CloseableHttpResponse response = this.httpClient.execute(httpGet);

        // 判断状态码是否为200
        if (response.getStatusLine().getStatusCode() >= 200 && response.getStatusLine().getStatusCode() <= 210) {
            // 返回响应体的内容
            return EntityUtils.toString(response.getEntity(), "UTF-8");
        }
        return null;
    }

    /**
     * crm专用
     * 不带参数的get请求，如果状态码为200，则返回body，如果不为200，则返回null
     *
     * @param url
     * @return
     * @throws Exception
     */
    public String doGetCrm(String url) throws Exception {
        // 声明 http get 请求
        HttpGet httpGet = new HttpGet(url);

        // 装载配置信息
        httpGet.setConfig(config);

        this.httpClient = this.crmConfig.getAuthHttp();

        // 发起请求
        CloseableHttpResponse response = this.httpClient.execute(httpGet);

        // 判断状态码是否为200
        if (response.getStatusLine().getStatusCode() >= 200 && response.getStatusLine().getStatusCode() <= 210) {
            // 返回响应体的内容
            return EntityUtils.toString(response.getEntity(), "UTF-8");
        }
        return null;
    }

    /**
     * 不带参数的get请求，如果状态码为200，则返回body，如果不为200，则返回null
     *
     * @param url
     * @return
     * @throws Exception
     */
    public String doGet(String url) throws Exception {
        // 声明 http get 请求
        HttpGet httpGet = new HttpGet(url);

        // 装载配置信息
        httpGet.setConfig(config);

//        this.httpClient = this.crmConfig.getAuthHttp();
        // 发起请求
        CloseableHttpResponse response = this.httpClient.execute(httpGet);

        // 判断状态码是否为200
        if (response.getStatusLine().getStatusCode() == 200) {
            // 返回响应体的内容
            return EntityUtils.toString(response.getEntity(), "UTF-8");
        }
        return null;
    }

    /**
     * 带参数的get请求，如果状态码为200，则返回body，如果不为200，则返回null
     *
     * @param url
     * @return
     * @throws Exception
     */
    public String doGet(String url, Map<String, Object> map) throws Exception {
        URIBuilder uriBuilder = new URIBuilder(url);

        if (map != null) {
            // 遍历map,拼接请求参数
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
            }
        }

        // 调用不带参数的get请求
        return this.doGet(uriBuilder.build().toString());

    }


    /**
     * 带参数的post请求
     * 如果状态码为200，则返回body，如果不为200，则返回null
     *
     * @param url
     * @param str
     * @return
     * @throws Exception
     */
    public String doPost(String url, String str,String header) throws Exception {
        // 声明httpPost请求
        HttpPost httpPost = new HttpPost(url);
        // 加入配置信息
        httpPost.setConfig(config);
        if(StringUtils.isBlank(header)){
            httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
        }else{
            httpPost.setHeader("Content-Type", header);

        }

        if (str != null) {
            // 判断map是否为空，不为空则进行遍历，封装from表单对象
            StringEntity stringEntity = new StringEntity(str, "utf-8");
            stringEntity.setContentEncoding("UTF-8");
            httpPost.setEntity(stringEntity);

            // 发起请求
            CloseableHttpResponse response = this.httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                return EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        }
        return null;
    }

    /**
     * CRM专用Post请求 增加Header.prefer return=representation
     * 带参数的post请求
     * 如果状态码为200，则返回body，如果不为200，则返回null
     *
     * @param url
     * @param str
     * @return
     * @throws Exception
     */
    public String doPostCrm(String url, String str) throws Exception {
        // 声明httpPost请求
        HttpPost httpPost = new HttpPost(url);
        // 加入配置信息
        httpPost.setConfig(config);
        httpPost.setHeader("Prefer", "return=representation");
        httpPost.setHeader("Content-Type", "application/json;charset=utf-8");

        if (str != null) {
            // 判断map是否为空，不为空则进行遍历，封装from表单对象
            System.out.println("合同Post请求String：" + str);
            StringEntity stringEntity = new StringEntity(str, "utf-8");
            stringEntity.setContentEncoding("UTF-8");
            httpPost.setEntity(stringEntity);

            //鉴权
            this.httpClient = this.crmConfig.getAuthHttp();
            // 发起请求
            CloseableHttpResponse response = this.httpClient.execute(httpPost);
            log.info("CRM请求返回字符串:" + response.toString());
            if (response.getStatusLine().getStatusCode() >= 200 && response.getStatusLine().getStatusCode() <= 210) {

                return EntityUtils.toString(response.getEntity(), "UTF-8");
            } else {
                log.info("CRM-error请求返回:" + EntityUtils.toString(response.getEntity(), "UTF-8"));
                return null;
            }
        }
        return null;
    }

    /**
     * CRM专用Post请求 增加Header.prefer return=representation 增加头部认证 MSCRMCallerID
     * 带参数的post请求
     * 如果状态码为200，则返回body，如果不为200，则返回null
     *
     * @param url
     * @param str
     * @return
     * @throws Exception
     */
    public String doPostCrmSingle(String url, String str, String header) throws Exception {
        // 声明httpPost请求
        HttpPost httpPost = new HttpPost(url);
        // 加入配置信息
        httpPost.setConfig(config);
        httpPost.setHeader("Prefer", "return=representation");
        httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
        httpPost.setHeader("MSCRMCallerID", header);

        if (str != null) {
            // 判断map是否为空，不为空则进行遍历，封装from表单对象
            StringEntity stringEntity = new StringEntity(str, "utf-8");
            stringEntity.setContentEncoding("UTF-8");
            httpPost.setEntity(stringEntity);

            //鉴权
            this.httpClient = this.crmConfig.getAuthHttp();
            // 发起请求
            CloseableHttpResponse response = this.httpClient.execute(httpPost);
            log.info("CRM请求返回字符串:" + response.toString());
            if (response.getStatusLine().getStatusCode() >= 200 && response.getStatusLine().getStatusCode() <= 210) {

                return EntityUtils.toString(response.getEntity(), "UTF-8");
            } else {
                log.info("CRM专用请求返回:" + response.getStatusLine().getReasonPhrase());
            }
        }
        return null;
    }

    /**
     * 删除crm记录
     * url中包含需要删除的实体(guid)
     */
    public String doDeleteCrm(String url) throws Exception {
        HttpDelete httpDelete = new HttpDelete(url);
        httpDelete.setConfig(config);
        httpDelete.setHeader("Prefer", "return=representation");
        httpDelete.setHeader("Content-Type", "application/json;charset=utf-8");
        //鉴权
        this.httpClient = this.crmConfig.getAuthHttp();
        CloseableHttpResponse response = this.httpClient.execute(httpDelete);
        log.info("CRM删除请求返回字符串:" + response.toString());
        if (response.getStatusLine().getStatusCode() == 204) {
            return "1";
        } else {
            log.info("CRM删除请求返回:" + response.getStatusLine().getReasonPhrase());
        }
        return null;
    }

    /**
     * 更新crm记录
     * url中必须包含对应的id
     */
    public String doUpdateCrm(String url, String str) throws Exception {
        HttpPatch httpPatch = new HttpPatch(url);
        httpPatch.setConfig(config);
        httpPatch.setHeader("Prefer", "return=representation");
        httpPatch.setHeader("Content-Type", "application/json;charset=utf-8");

        if (str != null) {
            // 判断map是否为空，不为空则进行遍历，封装from表单对象
            StringEntity stringEntity = new StringEntity(str, "utf-8");
            stringEntity.setContentEncoding("UTF-8");
            httpPatch.setEntity(stringEntity);

            //权限
            this.httpClient = this.crmConfig.getAuthHttp();
            // 发起请求
            CloseableHttpResponse response = this.httpClient.execute(httpPatch);
            if (response.getStatusLine().getStatusCode() >= 200 && response.getStatusLine().getStatusCode() <= 210) {
                return EntityUtils.toString(response.getEntity(), "UTF-8");
            } else {
                log.info("请求CRM异常:" + EntityUtils.toString(response.getEntity()));
            }
        }
        return null;
    }

    /**
     * 不带参数的post 请求
     *
     * @param url
     * @throws Exception
     */
    public void doPost(String url) throws Exception {
        this.doPost(url, null,null);
    }

}
